package com.heima.search.service.Impl;


import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.pojo.ApUserSearch;
import com.heima.model.user.pojo.ApUser;
import com.heima.search.service.ApUSerSearchService;
import com.heima.utils.common.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ApUSerSearchServiceImpl implements ApUSerSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存用户搜索历史
     */
    @Async
    @Override
    public void saveSearch(ApUserSearch userSearch) {
        //判断当前用户是否保存过用户id
        Query query = Query.query(Criteria.where("keyword").is(userSearch.getKeyword()).and("userId").is(userSearch.getUserId()));
        //查询数据库
        ApUserSearch one = mongoTemplate.findOne(query, ApUserSearch.class);
        if (one == null) {
            //没有保存过,则进行保存
            mongoTemplate.save(userSearch,"ap_user_search");
        }else {
            //如果保存过则更新搜索时间
            one.setCreatedTime(new Date());
            mongoTemplate.save(one,"ap_user_search");
        }

    }

    /**
     加载用户搜索历史列表
     @return
     */
    @Override
    public ResponseResult load(Integer pageSize) {

        //获取当前用户
        Integer userId = UserThreadLocal.getUserId();
        if(userId == 0){
            return ResponseResult.okResult(Collections.emptyList());
        }
        //根据用户查询数据，按照时间倒序
        Query query = Query.query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        query.limit(pageSize);
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 删除用户搜索历史
     * @param id
     */
    @Override
    public ResponseResult removeHistory(String id) {
        Query query = Query.query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query,ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
